﻿using EasyDDD.AdminModule.Domain.AggregateSysMenu;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;

namespace EasyDDD.AdminModule.Application.CommandsSysMenu
{
    [AutoMapperTo(typeof(SysMenu))]
    public record SysMenuUpdateCommand : Models.SysMenu, ICommand<SysMenu>
    {
        [JsonIgnore]
        public override bool IsDeleted { get; set; }
        [JsonIgnore]
        public override Guid TenantId { get; set; }


        [JsonPropertyName("rank")]
        public override int Sort { get; set; } = 1000;

        [JsonPropertyName("auths")]
        public override string Permission { get; set; } = string.Empty;
        public override string ExtJson { get; set; } = string.Empty;
    }
    public class SysMenuUpdateCommandValidator : AbstractValidator<SysMenuUpdateCommand>
    {
        public SysMenuUpdateCommandValidator(Repository.SysMenuRepository repository)
        {
            var query = repository.AsQueryable();

            RuleFor(x => x.Title).NotEmpty().MaximumLength(20)
                .WithErrorCode("标题不能为空");
            //RuleFor(x => x.Name).NotEmpty().MaximumLength(20)
            //    .WithErrorCode("路由名称不能为空");                               
            //RuleFor(x => x.Path).NotEmpty().MaximumLength(100)
            //    .WithErrorCode("路由路径不能为空");

            RuleFor(x => x).Must(x => !(x.MenuType == 0 && query.Any(e => e.Id != new SysMenuId(x.Id) && e.Title == x.Title)))
                .WithMessage("标题不能重复");
            RuleFor(x => x).Must(x => !(x.MenuType == 0 && query.Any(e => e.Id != new SysMenuId(x.Id) && e.Name == x.Name)))
                .WithMessage("Name不能重复");
            RuleFor(x => x).Must(x => !(x.MenuType == 0 && query.Any(e => e.Id != new SysMenuId(x.Id) && e.Path == x.Path)))
                .WithMessage("Path不能重复");
        }
    }
    public class SysMenuUpdateCommandHandler(
        IMapper mapper,
        Repository.SysMenuRepository repository,
        //Domain.SysMenuDomainService service,
        ILogger<SysMenuUpdateCommandHandler> logger)
        : ICommandHandler<SysMenuUpdateCommand, SysMenu>
    {
        public Task<SysMenu> Handle(SysMenuUpdateCommand request, CancellationToken cancellationToken)
        {
            logger.LogDebug("命令 SysMenuUpdateCommandHandler");
            var entity = mapper.Map<SysMenu>(request);
            return repository.UpdateAsync(entity, cancellationToken);
        }
    }
}
